<?php

namespace addons\shopro\controller;

use addons\shopro\service\OrderCode as OrderCodeService;
use app\admin\model\shopro\order\Order;

/**
 * 订单Code控制器
 */
class OrderCode extends Base
{
    /**
     * 获取订单的codes
     */
    public function getOrderCodes()
    {
        $orderId = $this->request->param('order_id');
        
        if (!$orderId) {
            $this->error('订单ID不能为空');
        }
        
        $order = Order::find($orderId);
        if (!$order) {
            $this->error('订单不存在');
        }
        
        $codes = OrderCodeService::getOrderCodes($order);
        
        $this->success('获取成功', [
            'order_id' => $order->id,
            'order_sn' => $order->sn,
            'codes' => $codes,
            'codes_string' => implode(',', $codes),
            'codes_count' => count($codes)
        ]);
    }

    /**
     * 验证code
     */
    public function validateCode()
    {
        $code = $this->request->param('code');
        
        if (!$code) {
            $this->error('Code不能为空');
        }
        
        $codeInfo = OrderCodeService::getCodeInfo($code);
        
        if (!$codeInfo) {
            $this->error('Code无效或不存在');
        }
        
        $this->success('Code验证成功', $codeInfo);
    }

    /**
     * 根据code查找订单
     */
    public function findOrderByCode()
    {
        $code = $this->request->param('code');
        
        if (!$code) {
            $this->error('Code不能为空');
        }
        
        $order = OrderCodeService::findOrderByCode($code);
        
        if (!$order) {
            $this->error('未找到相关订单');
        }
        
        $codes = OrderCodeService::getOrderCodes($order);
        
        $this->success('查找成功', [
            'order' => $order,
            'codes' => $codes,
            'codes_string' => implode(',', $codes)
        ]);
    }

    /**
     * 获取code统计信息
     */
    public function getCodeStats()
    {
        $stats = OrderCodeService::getCodeStats();
        
        $this->success('获取成功', $stats);
    }

    /**
     * 手动生成codes（管理员功能）
     */
    public function manualGenerate()
    {
        $orderId = $this->request->param('order_id');
        $count = $this->request->param('count', 1);
        
        if (!$orderId) {
            $this->error('订单ID不能为空');
        }
        
        if ($count <= 0 || $count > 100) {
            $this->error('生成数量必须在1-100之间');
        }
        
        try {
            $codes = OrderCodeService::manualGenerateCodes($orderId, $count);
            
            $this->success('生成成功', [
                'codes' => $codes,
                'codes_string' => implode(',', $codes),
                'count' => count($codes)
            ]);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
    }
}
